<?php
class duphpDB{
	
	private $link_ID=0;
	private $query_ID=0; 
	private $database='';	
	private $query_last='';
	
	function __construct($db_host,$db_user,$db_password,$database,$charset='UTF8'){		
		$this->database=$database;
		if(0==$this->link_ID)
			$this->link_ID=$connection=@mysql_connect($db_host, $db_user, $db_password, true) or $this->ShowErr('connection');		
		if(!mysql_query('use '.$database,$connection))
    		$this->ShowErr('selectdatabase');
    	mysql_query('set names '.$charset);    	
	}
	
	public function Execute($query){
		$this->IsConnect();		
		$this->query_last=$query;
		$this->query_ID=$resource=mysql_query($query,$this->link_ID) or $this->ShowErr('executequery',mysql_error());				
		return $resource;			
	}
	
	public function Result($query=false,$fetch_type='mysql_fetch_assoc'){		
		$result=array();
		if(!$query){
			$this->IsExecute();		
			$resource=$this->query_ID;
		}else{
			$resource=$this->Execute($query);
		}
		$num=mysql_num_rows($resource);
		if($num>0){			
			while($rows=$fetch_type($resource))$result[]=$rows;										
		}		
		mysql_free_result($resource);	
		return $result; 
	}
	
	public function ResultOne($query=false){
		$result=array();		
		$result=$this->Result($query);		
		if(count($result)>0)
			return $result[0];
	}
	
	public function CountRow($query=false){		
		return count($this->Result(!$query?$this->query_last:$query));
	}
	
	public function GetFields($table_name){
		$this->IsConnect();				
		return $this->Result(sprintf('SHOW COLUMNS FROM `%s`',$table_name));	
	}
	
	public function Update($table,$where,$field,$value=''){
		$data=array();
		if(is_string($field)&&$value!=''){
			$data=array($field=>$value);
		}elseif(is_array($field)){
			$data=$field;
		}
		if(count($data)==0) $this->ShowErr('updatedate');
		$query='UPDATE `%s` SET %s WHERE 1=1 AND %s';
		$item=array();
		foreach ($data as $k=>$v){
			$item[]=sprintf("`%s`='%s'",$k,$v);
		}
		return $this->Execute(sprintf($query,$table,implode(', ',$item),$where));		
	}
		
	private function IsConnect(){		
		if(0==$this->link_ID)
			$this->ShowErr('connection');				
	}
	private function IsExecute(){
		if(0==$this->link_ID)
			$this->ShowErr('executequery');		
	}
	//build it later
	private function ShowErr($msg_type,$err=''){
		switch ($msg_type){
			case 'executequery':
				echo $this->query_last;
				break;
			default:
				echo $msg_type;	
		}
		die('<br />'.$err);
	}
}	
class duphpAdmin extends duphpDB {
	
	private $url='';
	private $key='ID';
	private $fields=array();
	private $table_name='';
	private $field_list_temp=array();
	private $field_modify_temp=array();
	private $field_list=array();
	private $field_modify=array();
	private $field_fun=array();
	
	function __construct($db_host='',$db_user='',$db_password='',$database='',$charset='UTF8'){		
		if($db_host!=''&&$db_user!=''&&$db_password!=''&&$database!=''){			
			parent::__construct($db_host,$db_user,$db_password,$database,$charset);
		}		
	}
	//初始化，获得表中所有字段信息，获得主键
	private function Init($table_name){
		$fields=parent::GetFields($table_name);		
		$field_list=array();
		$field_modify=array();			
		foreach ($fields as $item){
			$field_names[$item['Field']]=$item;
			if($item['Key']=='PRI') 
				$this->key=$item['Field'];				
		}
		$this->fields=$field_names;
		//处理显示字段和修改字段		
		foreach ($this->field_list_temp as $field)
			$field_list[$field]=$field_names[$field];
		foreach ($this->field_modify_temp as $field)
			$field_modify[$field]=$field_names[$field];	
		$this->field_list=count($field_list)==0?$field_names:$field_list;
		$this->field_modify=count($field_modify)==0?$field_names:$field_modify;		
	}
	//显示列表页
	public function ShowListHtml($table=''){
		$table_name=$table==''?$this->table_name:$table;		
		$this->Init($table_name);
		$url=$this->GetUrl();		
		$key=$this->key;
		$field_names=$this->field_list;
		$select=count($this->field_list_temp)==0?'*':'`'.implode('`,`',$this->field_list_temp).'`';
		$tr_html=array();
		$td_html=array();
		$th_html=array();
		$result=parent::Result(sprintf('SELECT %s FROM `%s`',$select,$table_name));		
		foreach ($field_names as $name=>$item){
			$th_html[]=sprintf('<th>%s</th>',$name);
		}
		$th_html[]='<th>操作区</th>';
		$tr_html[]=sprintf("<tr>\n%s\n</tr>",implode("\n",$th_html));
		foreach ($result as $item){			
			foreach ($item as $k=>$v){				
				$td_html[]=sprintf(
							'<td>%s</td>',
							$field_names[$k]['Type']!='text'?$this->DealFieldByFun($k,$v):'很长很长的内容'
							);
			}
			$td_html[]=sprintf(
						'<td><a href="%sr[0]=modify&r[1]=%s" >修改</a> | <a href="%sr[0]=verifydelete&r[1]=%s" >删除</a></td>',
						$url,
						$item[$key],
						$url,
						$item[$key]
						);
			$tr_html[]=sprintf("<tr>\n%s\n</tr>",implode("\n",$td_html));
			$td_html=array();
		}		
		echo '<table>'.implode("\n",$tr_html).'</table>';
		return $this;
	}
	//显示修改页
	Public function ShowModifyHtml($value,$table=''){
		$table_name=$table==''?$this->table_name:$table;
		$this->Init($table_name);
		$url=$this->GetUrl();
		$return_url=$this->url;
		$key=$this->key;
		$field_names=$this->field_modify;
		$select=count($this->field_modify_temp)==0?'*':'`'.implode('`,`',$this->field_modify_temp).'`';
		$result=parent::ResultOne(sprintf("SELECT %s FROM `%s` WHERE `%s`='%s'",$select,$table_name,$key,$value));
		//HTML相关变量
		$html='';
		$legend_html=sprintf('<legend>修改%s为%s的条目</legend>',$key,$value);
		$form_html=sprintf('<form action="" method="post" id="form_%s" ></form>',$key);
		$submit_html=sprintf(
						"\n".'<p><input type="submit" id="submit_%s" value="确定修改"  />或者<a href="%s">返回</a></p>'."\n",
						$key,
						$return_url
						);
		$p=array();
		//处理数据
		foreach ($result as $k=>$v){
			$p[]=$this->DealValueHtml($k,$v);
		}
		//打印输出
		printf(
			"<fieldset>\n%s\n%s\n</fieldset>",
			$legend_html,
			sprintf(
				'<form action="%sr[0]=savemodify&r[1]=%s" method="post" id="form_%s" >%s%s</form>',
				$url,
				$value,
				$key,
				implode("\n",$p),
				$submit_html
				)
			);
		return $this;				
	}
	//执行修改
	public function SaveModify($post,$value,$table=''){
		$table_name=$table==''?$this->table_name:$table;
		$this->Init($table_name);
		//通过INIT获得下面各值
		$url=$this->GetUrl();
		$return_url=$this->url;
		$key=$this->key;
		$field_names=$this->fields;
		//执行
		$result=parent::Update($table_name,sprintf("`%s`='%s'",$key,$value),$post);
		if($result)
			printf('修改%s为%s的条目成功，<a href="%s" >返回列表</a>',$key,$value,$return_url);
		return $this;	
	}
	//显示确定删除选项
	public function VerifyDeleteHtml($value,$table=''){
		$table_name=$table==''?$this->table_name:$table;
		$this->Init($table_name);
		//通过INIT获得下面各值
		$url=$this->GetUrl();
		$return_url=$this->url;
		$key=$this->key;
		printf(
			'确定要删除%s为%s的条目？，[<a href="%sr[0]=dodelete&r[1]=%s" >确定删除</a>]　或者　[<a href="%s" >返回</a>]',
			$key,
			$value,
			$url,
			$value,
			$return_url
			);
		return $this;	
	}
	//执行删除条目
	public function Delete($value,$table=''){
		$table_name=$table==''?$this->table_name:$table;
		$this->Init($table_name);
		//通过INIT获得下面各值
		$url=$this->GetUrl();
		$return_url=$this->url;
		$key=$this->key;
		//生成SQL
		$query=sprintf("DELETE FROM `%s` WHERE `%s`='%s'",$table_name,$key,$value);
		$result=parent::Execute($query);
		if($result)
			printf('删除%s为%s的条目成功，<a href="%s" >返回列表</a>',$key,$value,$return_url);
		return $this;			
	}
	//设定当前URL
	public function SetUrl($url){
		$this->url=$url;
		return $this;
	} 
	//设定表名
	public function SetTable($table){
		$this->table_name=$table;
		return $this;
	}
	//自定义列表页显示字段，如不设定则全部显示
	public function SetFieldsInList($fields){
		if(is_array($fields))
			$this->field_list_temp=$fields;
		else 
			$this->field_list_temp=explode(',',$fields);
		return $this;	
	}
	//自定义修改条目，不设定除主键外全部可修改	
	public function SetFieldsInModify($fields){
		if(is_array($fields))
			$this->field_modify_temp=$fields;
		else 
			$this->field_modify_temp=explode(',',$fields);
		return $this;	
	}
	//引用外部函数处理字段
	public function SetFunction($field,$fun=''){
		if(is_array($field))
			$this->field_fun=$field;
		elseif(is_string($field)&&is_string($fun))	
			$this->field_fun[$field]=$fun;
		return $this;	
	}
	//集成，全自动，不推荐
	public function DoForAll(){
		$act=&$_GET['r'];
		switch (true){
			//修改
			case $act[0]=='modify'&&isset($act[1]):		
				$this->ShowModifyHtml($act[1]);
				break;
			//保存修改
			case $act[0]=='savemodify'&&isset($act[1])&&count($_POST)>0:
				$this->SaveModify($_POST,$act[1])->ShowListHtml();				
				break;
			//删除	
			case $act[0]=='verifydelete'&&isset($act[1]):
				$this->VerifyDeleteHtml($act[1])->ShowListHtml();				
				break;
			//执行删除
			case $act[0]=='dodelete'&&isset($act[1]):
				$this->Delete($act[1])->ShowListHtml();				
				break;	
			//显示列表
			default:				
				$this->ShowListHtml();
			break;
		}
		return $this;	
	}
	
	//处理字段显示方式，修改页
	private function DealValueHtml($field,$value){
		$fields=$this->fields;		
		$html='';		
		$p='<p><label>'.$field.'</label><br />%s</p>';
		if($fields[$field]['Null']=='NO')
			$p='<p><label>'.$field.'(必填)</label><br />%s</p>';
		$textarea='<textarea name="%s" id="%s" cols="100" rows="10">%s</textarea>';
		$input='<input type="text" name="%s" id="%s" value="%s" />';
		$text='<strong>%s</strong>';
		switch ($fields[$field]['Type']){
			case 'text':
				$html=sprintf($p,sprintf($textarea,$field,$field,$value));
				break;
			default:
				$html=sprintf($p,sprintf($input,$field,$field,$value));
		}
		if($fields[$field]['Key']=='PRI')
			$html=sprintf($p,sprintf($text,$value));
		return $html;
	}
	//引用外部函数处理字段
	private function DealFieldByFun($key,$value){
		$field_fun=$this->field_fun;
		if(isset($field_fun[$key])&&function_exists($field_fun[$key]))
			return $field_fun[$key]($value);
		else 
			return $value;	
	}
	//获取当前URL，返回后面带?或者&的URL，并给$this->url赋值当前URL
	private function GetUrl(){
		$this->url=$url=$this->url==''?'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']:$this->url;		
		return strpos($url,'?')>0?$url.'&':$url.'?';
	}

}
?>